package com.darkidiot.session.IDGenerator;

import com.darkidiot.session.util.ShortUuidGenerator;
import com.darkidiot.session.util.WebUtil;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 分布式ID生成策略接口
 * Copyright (c) for darkidiot
 * Date:2017/4/14
 * Author: <a href="darkidiot@icloud.com">darkidiot</a>
 * School: CUIT
 * Desc:
 */
public class DefaultSessionIdGenerator implements SessionIdGenerator {
    private static final Character SEP = '-';
    private final String hostIpMd5;

    public DefaultSessionIdGenerator() {
        String hostIp;
        try {
            hostIp = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            hostIp = ShortUuidGenerator.generateShortUuid();
        }
        this.hostIpMd5 = Hashing.md5().hashString(hostIp, Charsets.UTF_8).toString().substring(0, 8);
    }

    /**
     * 通过远端ip-md5+主机ip-mds+二进制时间戳+8位UUID生成唯一ID
     *
     * @param request
     * @return
     */
    @Override
    public String generateId(HttpServletRequest request) {
        StringBuilder builder = new StringBuilder(30);
        String remoteIpMd5 = Hashing.md5().hashString(WebUtil.getClientIp(request), Charsets.UTF_8).toString().substring(0, 8);
        builder.append(remoteIpMd5).append(SEP)
                .append(this.hostIpMd5).append(SEP).
                append(Long.toHexString(System.currentTimeMillis())).append(SEP).
                append(ShortUuidGenerator.generateShortUuid());
        return builder.toString();
    }
}
